package com.github.szhittech;


import com.github.szhittech.service.AppPluginImpl;
import com.github.szhittech.service.DependencyImpl;
import com.github.szhittech.service.ProjectExecuteImpl;
import com.github.szhittech.service.api.ApiService;
import com.github.szhittech.service.api.http.SimpleHttpUtils;
import com.github.szhittech.service.api.inter.IAppPlugin;
import com.github.szhittech.service.api.inter.IDependency;
import com.github.szhittech.service.api.inter.IProjectExecute;
import com.github.szhittech.service.prop.Properties;
import com.github.szhittech.util.Logc;
import com.github.szhittech.util.Util;

import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.artifacts.maven.MavenPom;
import org.gradle.api.artifacts.maven.MavenResolver;
import org.gradle.api.internal.artifacts.ImmutableModuleIdentifierFactory;
import org.gradle.api.internal.artifacts.Module;
import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectPublication;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectPublicationRegistry;
import org.gradle.api.internal.artifacts.mvnsettings.LocalMavenRepositoryLocator;
import org.gradle.api.internal.artifacts.mvnsettings.MavenSettingsProvider;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.plugins.DslObject;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.plugins.MavenPlugin;
import org.gradle.api.plugins.MavenRepositoryHandlerConvention;
import org.gradle.api.tasks.Upload;
import org.gradle.configuration.project.ProjectConfigurationActionContainer;
import org.gradle.internal.DisplayName;
import org.gradle.internal.Factory;
import org.gradle.internal.logging.LoggingManagerInternal;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.inject.Inject;

import groovy.lang.GroovyClassLoader;

public class MainPlugin implements Plugin<ProjectInternal> {
    private final Factory<LoggingManagerInternal> loggingManagerFactory;
    private final FileResolver fileResolver;
    private final ProjectPublicationRegistry publicationRegistry;
    private final ProjectConfigurationActionContainer configurationActionContainer;
    private final MavenSettingsProvider mavenSettingsProvider;
    private final LocalMavenRepositoryLocator mavenRepositoryLocator;
    private final ImmutableModuleIdentifierFactory moduleIdentifierFactory;
    private ProjectInternal project;
    public static final String INSTALL_TASK_NAME = "install";

    static {
        ApiService.registerService(IDependency.class, DependencyImpl.class);
        ApiService.registerService(IProjectExecute.class, ProjectExecuteImpl.class);
        ApiService.registerService(IAppPlugin.class, AppPluginImpl.class);
    }

    @Inject
    public MainPlugin(Factory<LoggingManagerInternal> loggingManagerFactory,
                      FileResolver fileResolver,
                      ProjectPublicationRegistry publicationRegistry,
                      ProjectConfigurationActionContainer configurationActionContainer,
                      MavenSettingsProvider mavenSettingsProvider,
                      LocalMavenRepositoryLocator mavenRepositoryLocator,
                      ImmutableModuleIdentifierFactory moduleIdentifierFactory) {
        this.loggingManagerFactory = loggingManagerFactory;
        this.fileResolver = fileResolver;
        this.publicationRegistry = publicationRegistry;
        this.configurationActionContainer = configurationActionContainer;
        this.mavenSettingsProvider = mavenSettingsProvider;
        this.mavenRepositoryLocator = mavenRepositoryLocator;
        this.moduleIdentifierFactory = moduleIdentifierFactory;
//        Logc.e("============MainPlugin==========>>>>>>>>");
    }

    /*@Inject
    public MainPlugin(Factory<LoggingManagerInternal> loggingManagerFactory, FileResolver fileResolver, ProjectPublicationRegistry publicationRegistry, ProjectConfigurationActionContainer configurationActionContainer, MavenSettingsProvider mavenSettingsProvider, LocalMavenRepositoryLocator mavenRepositoryLocator) {
        this.loggingManagerFactory = loggingManagerFactory;
        this.fileResolver = fileResolver;
        this.publicationRegistry = publicationRegistry;
        this.configurationActionContainer = configurationActionContainer;
        this.mavenSettingsProvider = mavenSettingsProvider;
        this.mavenRepositoryLocator = mavenRepositoryLocator;
        Logc.e("============MainPlugin==========>>>>>>>>");
    }*/


    public ImmutableModuleIdentifierFactory getModuleIdentifierFactory() {
        return moduleIdentifierFactory;
    }

    public ProjectConfigurationActionContainer getConfigurationActionContainer() {
        return configurationActionContainer;
    }

    public ProjectInternal getProject() {
        return project;
    }

    public ProjectPublicationRegistry getPublicationRegistry() {
        return publicationRegistry;
    }

    @Override
    public void apply(ProjectInternal projectInternal) {
        Logc.project = projectInternal;


        try {
            String script="com.github.szhittech.Mavens";//groovy script
            ClassLoader parent =ClassLoader.getSystemClassLoader();
            GroovyClassLoader loader = new GroovyClassLoader(parent);
            Class<?> clazz = loader.parseClass(script);
            System.out.println("=------------>"+clazz);
            //projectInternal.getPlugins().apply(clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }

        projectInternal.getPlugins().apply(MavenPluginExt.class);

//        project = projectInternal;
////        project.getPluginManager().apply("maven");
//        Logc.project = projectInternal;
//        IAppPlugin appPlugin = ApiService.getInstance(IAppPlugin.class);
//        if (appPlugin != null) {
//            appPlugin.onAppApply(this);
//        }
////        Logc.e("============apply==========>>>>>>>>");
//        //configureUploadArchivesTask(projectInternal);
//
//        configureInstall(project);
    }

    /*@Override
    public void apply(Project project) {
        Logc.project = project;
        IAppPlugin appPlugin = ApiService.getInstance(IAppPlugin.class);
        if (appPlugin != null) {
            appPlugin.onAppApply(project);
        }
    }*/

    private void configureInstall(Project project) {
        Upload installUpload = project.getTasks().create(INSTALL_TASK_NAME, Upload.class);
        Configuration configuration = project.getConfigurations().getByName(Dependency.ARCHIVES_CONFIGURATION);
        installUpload.setConfiguration(configuration);
        MavenRepositoryHandlerConvention repositories = new DslObject(installUpload.getRepositories()).getConvention().getPlugin(MavenRepositoryHandlerConvention.class);
        repositories.mavenInstaller();
        installUpload.setDescription("Installs the 'archives' artifacts into the local Maven repository.");
    }

    private void configureUploadArchivesTask(ProjectInternal projectInternal) {
        configurationActionContainer.add(new Action<Project>() {
            public void execute(Project project) {
                Logc.e("============configureUploadArchivesTask==========>>>>>>>>");
                Upload uploadArchives = (Upload) project.getTasks().withType(Upload.class).findByName("uploadArchives");
                if (uploadArchives != null) {
                    ConfigurationInternal configuration = (ConfigurationInternal) uploadArchives.getConfiguration();
                    Module module = configuration.getModule();
                    Iterator var5 = uploadArchives.getRepositories().withType(MavenResolver.class).iterator();
                    while (var5.hasNext()) {
                        MavenResolver resolver = (MavenResolver) var5.next();
                        MavenPom pom = resolver.getPom();
                        Logc.e("============configureUploadArchivesTask===>>>>>>" + pom.getArtifactId());
                        Logc.e("============configureUploadArchivesTask===>>>>>>" + pom.getGroupId());
                        Logc.e("============configureUploadArchivesTask===>>>>>>" + pom.getVersion());
//                        ModuleVersionIdentifier publicationId = new DefaultModuleVersionIdentifier(pom.getGroupId().equals("unknown") ? module.getGroup() : pom.getGroupId(), pom.getArtifactId().equals("empty-project") ? module.getName() : pom.getArtifactId(), pom.getVersion().equals("0") ? module.getVersion() : pom.getVersion());
//                        MainPlugin.this.publicationRegistry.registerPublication(project.getPath(), new DefaultProjectPublication(publicationId));
                        publicationRegistry.registerPublication(projectInternal, new ProjectPublication() {
                            @Override
                            public DisplayName getDisplayName() {
                                return null;
                            }
                        });
                    }

                }
            }
        });
    }


    public static void main(String[] args) throws IOException {
        String url = "https://oss.sonatype.org/content/repositories/snapshots/com/github/szhittech/hetbasicsdk/1.0.3-SNAPSHOT1/";
        int code = Util.ping(30000, url);
        System.out.println("=======>" + code);
    }

    private static void getUrl() {
        //String url = "https://oss.sonatype.org/content/repositories/snapshots/com/github/szhittech/";
        String url = "https://www.baidu.com";
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("username", Properties.SVNUSERNME);
            headers.put("password", Properties.SVNPASSWORD);
            String msg = SimpleHttpUtils.get(url, headers);
            System.err.println(">>>>>>>>>>>>>>>>>>>>>" + msg);
            //return new Gson().fromJson(msg, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void getHtml() throws IOException {
        //String url = "https://oss.sonatype.org/content/repositories/snapshots/com/github/szhittech/";
        String url = "https://www.baidu.com";
        Document document = Jsoup.connect(url).get();
        Elements links = document.select("a[href]");
        for (Element link : links) {
            System.out.println("link : " + link.attr("href"));
            System.out.println("text : " + link.text());
        }
    }

}
